import { useRef, useState } from 'react';
import type { ActionType } from '@ant-design/pro-components';
import type { FormInstance } from 'antd';
import type { PcTableProps } from '..';

interface UsePcTableOptions<T> {
  /** 默认分页大小 */
  defaultPageSize?: number;
  /** 创建记录的模板 */
  createRecordTemplate?: () => T;
  /** 保存回调 */
  onSave?: (key: React.Key, row: T) => Promise<boolean>;
}

/**
 * PcTable 的自定义 Hook
 * @template T - 表格数据类型
 */
const usePcTable = <T extends Record<string, any>>(options: UsePcTableOptions<T>) => {
  const {
    defaultPageSize = 10,
    createRecordTemplate,
    onSave,
  } = options;

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [editableKeys, setEditableKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
  });

  // 处理分页变化
  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize,
    }));
  };

  // 更新数据源
  const updateDataSource = (data: T[], total: number) => {
    setDataSource(data);
    setPagination(prev => ({
      ...prev,
      total,
    }));
  };

  // 表格配置
  const tableConfig: Omit<PcTableProps<T>, 'columns' | 'rowKey'> = {
    dataSource,
    loading,
    actionRef,
    formRef,
    editableKeys,
    setEditableKeys,
    pagination: {
      ...pagination,
      onChange: handlePaginationChange,
    },
    createRecordTemplate,
    onSave,
    onCancel: (key: React.Key) => {
      const record = dataSource.find(item => item.id === key);
      if (record?.id.toString().startsWith('temp_')) {
        // 如果是新增的临时记录，从数据源中移除
        updateDataSource(dataSource.filter(item => item.id !== key), pagination.total);
      }
      setEditableKeys([]);
    },
  };

  return {
    tableConfig,
    actionRef,
    formRef,
    dataSource,
    loading,
    pagination,
    setTableLoading: setLoading,
    updateDataSource,
    setEditableRowKeys: setEditableKeys,
  };
};

export default usePcTable; 